package com.xbw.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ktt.bean.Bis_custom_user;
import com.sjh.vo.Bis_bisiness_order;
import com.spc.miaodi.AccountInfo;
import com.xbw.bean.Bis_Shop;
import com.xbw.bean.Bis_shop_post;
import com.xbw.bean.Sys_User;
import com.xbw.service.ShopInfoService;
import com.xbw.service.ShopService;
import com.zsy.bean.Bis_Shop_User;
import com.zsy.service.Bis_Shop_PostService;
import com.zsy.service.Bis_Shop_UserService;

@Controller
@RequestMapping("shop")
public class ShopController {
    @Autowired
    private Bis_Shop_UserService bsu;
	@Autowired
	private ShopService sher;
    @Autowired
    private ShopInfoService sf;
	//��ת�����̱�
	@RequestMapping("listAll")
	public ModelAndView listAll(HttpServletRequest request,@RequestParam(value="page",defaultValue="1")int page){
		ModelAndView md=new ModelAndView();
		Map<String, Object> map=remap(request);
		 PageHelper.startPage(page, 5);
		 List<Bis_Shop> list=sher.listAll(map);
		 PageInfo<Bis_Shop> info=new PageInfo<>(list);
		 md.addObject("info", info);
		 md.addObject("map", map);
		 md.setViewName("bis_shop/shops");
		return  md; 
	}
	//��װģ����ѯ�ķ���
	private Map<String, Object>  remap(HttpServletRequest request){
		Map<String, Object> map=new HashMap<String,Object>();
        map.put("shop_id", request.getParameter("shop_id"));
        map.put("shop_name", request.getParameter("shop_name"));
        map.put("show_status", request.getParameter("show_status"));
        map.put("account", request.getParameter("account"));
        map.put("shop_license", request.getParameter("shop_license"));
		return map;
	}
	//��ת���̼�����ҳ��
		@RequestMapping("/insert")
		public String insert(Model md,HttpServletRequest request){
			 List<Bis_Shop_User> list=sher.getshopuser(reusermap(request));
			 md.addAttribute("list", list);
			return  "bis_shop/shopadd";
		}
		//bis_shop����
				@RequestMapping("/insertshop")
				public String insertshop(Bis_Shop bs,HttpServletRequest req,@RequestParam("file")MultipartFile file,HttpSession sess){
					 String path=req.getRealPath("/upload");
					  File fe=new File(path);
					  if(file.getOriginalFilename()==null||file.getOriginalFilename()==""){
						  bs.setShop_detail_image(req.getParameter("photoname"));
						  bs.setShop_image(req.getParameter("photoname")); 
					   } else{
					  if(!fe.exists()){
						  fe.mkdirs();
					  }
					   Date date=new Date();
					   SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
					   SimpleDateFormat sdf2=new SimpleDateFormat("yyyyMMddHHmmss");
					   File dir=new File(fe.getPath(),sdf.format(date));  
					   if(!dir.exists()){
						   dir.mkdirs();
					   }
						   File newfile=new File(dir.getPath(),file.getOriginalFilename());
						   if(!newfile.exists()){
							   try {
								newfile.createNewFile();
							} catch (IOException e) {
								e.printStackTrace();
							}
						   }
						   try {
							file.transferTo(newfile);
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
						  File codefile=new File(dir.getPath(),sdf2.format(date)+"img.png");
						  if(!newfile.exists()){
							   try {
								newfile.createNewFile();
							} catch (IOException e) {
								e.printStackTrace();
							}
						   }
						  if(req.getParameter("shop_id")==null){
							  String str=getstr(bs);
							  CraeteQRCode.get(codefile,str);
							  bs.setShop_qrcode("/upload/"+dir.getName()+"/"+codefile.getName()); 
						  }
						   bs.setShop_detail_image("/upload/"+dir.getName()+"/"+newfile.getName()); 
						   bs.setShop_image("/upload/"+dir.getName()+"/"+newfile.getName()); 
					   } 
					 if(req.getParameter("shop_id")!=null){
						 sher.editshop(bs);
					 }else{
						 bs.setShop_id(getid());
						 bs.setShop_type("1");
						 Sys_User user=(Sys_User)sess.getAttribute("sysuser");
						 bs.setCreate_user_id(user.getUser_id());
						 Date date=new Date();
						 bs.setCreate_time(date);
						 bs.setSort_no(1);
						 sher.save(bs); 
					 }
					return  "redirect:/shop/listAll";
				}
	 //�����̼��޸�ҳ��
				@RequestMapping("/editshop/{id}")
				public String  editshop(@PathVariable("id")String id, Model model,HttpServletRequest request){
					 List<Bis_Shop_User> list=sher.getshopuser(reusermap(request));
					 Bis_Shop bs=sher.getByShop_id(id);
					 model.addAttribute("bs", bs);
					 model.addAttribute("list", list);
					return  "bis_shop/shopedit";
				}
				//ɾ��
				@RequestMapping("/deleteshop/{id}")
				public String  deleteshop(@PathVariable("id")String id, Model model){
					    sher.delete(id);
					return  "redirect:/shop/listAll";
				}
				
	  //��ת��������
	@RequestMapping("/listuser")
	public ModelAndView listuser(HttpServletRequest request,@RequestParam(value="page",defaultValue="1")int page){
		ModelAndView md=new ModelAndView();
		Map<String, Object> map=reusermap(request);
		 PageHelper.startPage(page, 5);
		 List<Bis_Shop_User> list=sher.getshopuser(map);
		 PageInfo<Bis_Shop_User> info=new PageInfo<>(list);
		 md.addObject("info", info);
		 md.addObject("map", map);
		 md.setViewName("bis_shop/shopuser");
		return  md;
	} 
	private Map<String, Object>  reusermap(HttpServletRequest request){
		Map<String, Object> map=new HashMap<String,Object>();
		 map.put("user_type", "1");
		 map.put("is_del", "0");
        map.put("account", request.getParameter("account"));
        map.put("username", request.getParameter("username"));
        map.put("status", request.getParameter("status"));
        map.put("mobile", request.getParameter("mobile"));
        map.put("idno", request.getParameter("idno"));
        map.put("phone", request.getParameter("phone"));
		return map;
	}
	//��ת����������ҳ��
	@RequestMapping("/add")
	public String add(){
		return  "bis_shop/shopuseradd";
	}
	
	//bis_shop_user����
	@RequestMapping("/save")
	public String save(Bis_Shop_User shopuser,HttpSession sess,@RequestParam("file")MultipartFile file,HttpServletRequest req){
		 String path=req.getRealPath("/upload");
		  File fe=new File(path);
		  if(file.getOriginalFilename()==null||file.getOriginalFilename()==""){
			  shopuser.setPhoto(req.getParameter("photoname"));
		   } else{
		  if(!fe.exists()){
			  fe.mkdirs();
		  }
		   Date date=new Date();
		   SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
		   File dir=new File(fe.getPath(),sdf.format(date));  
		   if(!dir.exists()){
			   dir.mkdirs();
		   }
			   File newfile=new File(dir.getPath(),file.getOriginalFilename());
			   if(!newfile.exists()){
				   try {
					newfile.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			   }
			   try {
				file.transferTo(newfile);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			   shopuser.setPhoto("/upload/"+dir.getName()+"/"+newfile.getName()); 
		   } 
		  if(req.getParameter("shop_user_id")!=null){
			  sher.update(shopuser);
		  }else{
			  shopuser.setShop_user_id(getid());
				shopuser.setUser_type("1");
				shopuser.setIs_del("0");
				shopuser.setPost_code("00");
				Sys_User user=(Sys_User)sess.getAttribute("sysuser");
				shopuser.setCreate_user_id(user.getUser_id());
				Date date=new Date();
				shopuser.setCreate_time(date);
				shopuser.setMobile(shopuser.getPhone());
				Object pad=pas(shopuser.getAccount(),shopuser.getPhone());
				 shopuser.setPassword(pad.toString());
				 sher.insert(shopuser); 
		  }
		return  "redirect:/shop/listuser";
	}
	//���ص�ұ�
	@RequestMapping("/revert")
	public String revert(){
		return  "redirect:/shop/listuser";
	}
	//���ص��̱�
	@RequestMapping("/re")
	public String re(){
		return  "redirect:/shop/listAll";
	}
	//���������޸�ҳ��
	@RequestMapping("/edit/{id}")
	public String  edit(@PathVariable("id")String id, Model model){
		 Bis_Shop_User user=bsu.getById(id);
		 model.addAttribute("user", user);
		return  "bis_shop/shopuseredit";
	}
//	//�޸�
//	@RequestMapping("/update")
//	public String update(Bis_Shop_User shopuser){
//		 sher.update(shopuser);
//		return  "redirect:/shop/listuser";
//	}
	//ɾ��
	@RequestMapping("/delete/{id}")
	public String  delete(@PathVariable("id")String id, Model model){
		    sher.updatetype(id);
		return  "redirect:/shop/listuser";
	}
	//��װid
	private String getid(){
		SimpleDateFormat sdf=new SimpleDateFormat("yyMMddHHmmss");
		String str=sdf.format(new Date());
		Random random=new Random();
		int num= random.nextInt(9999)+1000;
		String id=str+num; 
		return id;
	}
	//��ת���޸�����ҳ��
	@RequestMapping("/editpas/{id}")
	public String  editpas(@PathVariable("id")String id, Model model){
		 Bis_Shop_User user=bsu.getById(id);
		 model.addAttribute("user", user);
		return  "bis_shop/editpas";
	}
	//�޸�����
	@RequestMapping("/uppas")
	@ResponseBody  //�첽�����
	public String  uppas(String id,String password,String phone,String account){
		  Map<String,Object> map=new HashMap<String,Object>();
		  map.put("password",password );
		  map.put("id", id);
		  sher.pas(map);
		return  "a";
	}
	//�����鿴����
	@RequestMapping("/xq")
	public String  xq(Model model,HttpServletRequest request){
		String shop_id=request.getParameter("shopid");
		model.addAttribute("shopid", shop_id);
		return  "xq/shopinfo";
	}
	//���̻�����Ϣ
	@RequestMapping("/basicinfo")
	public String basicinfo(Model model,HttpServletRequest request){
		List<Bis_Shop_User> list=sher.getshopuser(reusermap(request));
		String shop_id=request.getParameter("shop_id");
		Bis_Shop shop=sher.getByShop_id(shop_id);
		model.addAttribute("bs",shop);
		model.addAttribute("list", list);
		return "xq/shopinfolist";
	}
	//Ա��������Ϣ
	@RequestMapping("/elist")
	public String elist(Model model,HttpServletRequest request){
		String shop_id=request.getParameter("shop_id");
		Map<String, Object> map=new HashMap<>();
		map.put("shop_id", shop_id);
	List<Bis_Shop_User> list=sf.listuser(map);
	model.addAttribute("list", list);
		return "xq/elist";
	}
	//�˿ͻ�����Ϣ
	@RequestMapping("/clist")
	public String clist(Model model,HttpServletRequest request){
		String shop_id=request.getParameter("shop_id");
		Map<String, Object> map=new HashMap<>();
		map.put("shop_id", shop_id);
	List<Bis_custom_user> list=sf.listbcu(map);
	model.addAttribute("list", list);
		return "xq/clist";
	}
	//跳到订单详情
	@RequestMapping("/slist")
	public String slist(Model model,HttpServletRequest request){
		String shop_id=request.getParameter("shop_id");
		Map<String, Object> map=new HashMap<>();
		map.put("shop_id", shop_id);
	List<Bis_bisiness_order> list=sf.listorder(map);
	  model.addAttribute("list", list);
		return "xq/slist";
	}
	//跳到财务详情
	@RequestMapping("/mlist")
	public String mlist(Model model,HttpServletRequest request){
		String shop_id=request.getParameter("shop_id");
		Map<String, Object> map=new HashMap<>();
		map.put("shop_id", shop_id);
		List<Bis_bisiness_order> list=sf.listorder(map);
		  model.addAttribute("list", list);
		return "xq/mlist";
	}
	//生成店主密码
	public Object pas(String id,String phone){
		Random random=new Random();
		int num= random.nextInt(999999)+1000;
		System.out.println("店主密码:"+num);
			try{
				 AccountInfo.execute();
				 com.spc.miaodi.IndustrySMS.execute(phone,num+"");
			 }catch(Exception e){
				 e.printStackTrace();
			 }	
		
		String hashAlgorithName="MD5";
		//��ֵ
		Object salt=ByteSource.Util.bytes(id);
		//���ܴ���
		int count=1024;
		//���м���
		Object result=new SimpleHash(hashAlgorithName, num+"",salt,count);
		System.out.println("result:"+result);
		return result;
	}
	//验证账号重复
		@RequestMapping("/pas")
		public void  pas(HttpServletRequest request,HttpServletResponse response){
			Map<String, Object> ma=reusermap(request);
			boolean bl=sher.getinformation(ma);
			Map map=new HashMap<>();
			map.put("valid", bl);  
			resjson(response, map);
		}
		
	
		 private void resjson(HttpServletResponse response,Object obj){
		    	ObjectMapper  om=new ObjectMapper();
		    	try {
					String json=om.writeValueAsString(obj);
					System.out.println(json);
					PrintWriter out=response.getWriter();
					out.write(json);
					out.flush();
					out.close();
					return;
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
		    }
		 //二维码名片格式
	   private String getstr(Bis_Shop bs){
		   String str="BEGIN:VCARD"+"\n"+
					  "VERSION:3.0"+"\n"+
					  "  FN:"+bs.getShop_name()+"\n"+
					  " TEL;CELL;VOICE:"+bs.getShop_phone()+"\n"+
					  "ADR;WORK;POSTAL:"+bs.getShop_address()+"\n"+
					 " END:VCARD";
		   return   str;
		   
	   }
	 
}



